package com.mynews.crashhandler;

import android.os.Build;
import android.os.Process;
import android.util.Log;

import com.mynews.utils.Constant;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Created by bomei on 2017/7/1.
 */

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static final String TAG = CrashHandler.class.getSimpleName();
    private static CrashHandler mCrashHandler;
    private CrashHandler(){
    }

    /**
     * 单列模式 全局只有一个
     * @return
     */
    public static CrashHandler getInstance(){
        if(mCrashHandler == null){
            mCrashHandler = new CrashHandler();
        }
        return mCrashHandler;
    }

    public void init(){
        Thread.setDefaultUncaughtExceptionHandler(this);
    }


    /**
     * 核心方法，当程序出现crash的时候回调
     * @param thread
     * @param throwable
     */
    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        Log.e(TAG, "uncaughtException: CrashHanlder捕获中..." );

        String logName = "_log.txt";
        File logFile = new File(Constant.Log_PATH);
        if(!logFile.exists()){
            logFile.mkdirs();
        }
        PrintWriter printWriter = null;
        StringBuffer stringBuffer = new StringBuffer();
        String device_model = Build.MODEL; // 设备型号
        int version_sdk = Build.VERSION.SDK_INT; // 设备SDK版本
        String version_release = Build.VERSION.RELEASE; // 设备的系统版本
        try {
            printWriter = new PrintWriter(new File(Constant.Log_PATH +File.separator + logName));
            stringBuffer.append("log==》time: "+new Date())
                    .append("\n")
                    .append("device_model: ")
                    .append(device_model)
                    .append("\n")
                    .append("version_sdk: ")
                    .append(version_sdk)
                    .append("\n")
                    .append("version_release: ")
                    .append(version_release)
                    .append("\n")
                    .append(throwable.getMessage());
            StackTraceElement[] stackTrace = throwable.getStackTrace();
            for (StackTraceElement s : stackTrace) {
                stringBuffer.append("file:").append(s.getFileName())
                        .append(" class:").append(s.getClassName())
                        .append(" method:").append(s.getMethodName())
                        .append(" line:").append(s.getLineNumber()).append("\n");
            }
            printWriter.println(stringBuffer.toString());
            printWriter.close();

            //上传到服务器
            //......
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        throwable.printStackTrace();
        //这里可以配置 崩溃之后跳转到开始页面之类的
        android.os.Process.killProcess(Process.myPid());//杀死进程，关闭程序
    }
}
